/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.chlitina.store.modules.inventory.web;

import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.chlitina.store.common.config.Global;
import com.chlitina.store.common.mapper.JsonMapper;
import com.chlitina.store.common.persistence.Page;
import com.chlitina.store.common.web.BaseController;
import com.chlitina.store.modules.base.entity.StoreCare;
import com.chlitina.store.modules.base.entity.StoreProduct;
import com.chlitina.store.modules.base.entity.StoreSelfProduct;
import com.chlitina.store.modules.base.service.StoreProductService;
import com.chlitina.store.modules.expert.entity.Product;
import com.chlitina.store.modules.inventory.entity.StoreInventoryAlert;
import com.chlitina.store.modules.inventory.service.StoreInventoryAlertService;
import com.chlitina.store.modules.message.entity.StoreInventoryAlertMessage;
import com.chlitina.store.modules.sys.entity.Store;
import com.chlitina.store.modules.sys.utils.StoreUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

/**
 * 库存盘点预警Controller
 * @author lvbo
 * @version 2013-11-22
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH+"/inventory/storeInventoryAlert")
public class StoreInventoryAlertController extends BaseController {

	@Autowired
	private StoreInventoryAlertService storeInventoryAlertService;
	@Autowired
	private StoreProductService storeProductService;
	
	@ModelAttribute
	public StoreInventoryAlert get(@RequestParam(required=false) Long id) {
		if (id != null){
			return storeInventoryAlertService.get(id);
		}else{
			return new StoreInventoryAlert();
		}
	}
	
	@RequestMapping(value = {"list", ""})
	public String list(StoreInventoryAlert storeInventoryAlert, HttpServletRequest request, HttpServletResponse response, Model model) {
		Store store = StoreUtils.getStore();
		if (store != null){
			storeInventoryAlert.setStore(store);
		}
		String procuctName = request.getParameter("procuctName");
		Page<StoreInventoryAlert> page = new Page<StoreInventoryAlert>(request, response);
        List<StoreInventoryAlert> list = storeInventoryAlertService.find(new Page<StoreInventoryAlert>(request, response), storeInventoryAlert); 
        List<StoreInventoryAlert> pageList = Lists.newArrayList();
        if (procuctName == null) {
        	pageList = list;
		} else {
			for (StoreInventoryAlert alert : list) {
				StoreProduct storeProduct = alert.getStoreProduct();
				String name = "";
				if (storeProduct.getProduct_type() == StoreProduct.TYPE_SYS) {
					name = storeProduct.getProduct().getName();
				} else {
					name = storeProduct.getStoreSelfProduct().getName();
				}
				int index = name.indexOf(procuctName);
				if (index > -1) {
					pageList.add(alert);
				}
			}
		}
        page.updatePage(pageList);
        model.addAttribute("procuctName", procuctName);
        model.addAttribute("page", page);
		return "modules/inventory/storeInventoryAlertList";
	}
	@RequestMapping(value = "check")
	public String check(StoreInventoryAlert storeInventoryAlert, HttpServletRequest request, HttpServletResponse response, Model model) {
		Store store = StoreUtils.getStore();
		if (store != null){
			storeInventoryAlert.setStore(store);
		}
		Page<StoreInventoryAlertMessage> page = new Page<StoreInventoryAlertMessage>(request, response);
		List<StoreInventoryAlert> list = storeInventoryAlertService.findNeedAlertStoreProduct();
		List<StoreInventoryAlertMessage> msglist = Lists.newArrayList();
		for (StoreInventoryAlert sia : list) {
			StoreInventoryAlertMessage siam = new StoreInventoryAlertMessage();
			siam.setStoreInventoryAlert(sia);
			int size = storeInventoryAlertService.getProductAmount(sia.getStoreProduct().getId());
			siam.setSaleNumber(size);
			msglist.add(siam);
		}
		page.updatePage(msglist);
		model.addAttribute("page", page);
		return "modules/message/storeInventoryAlertMessage";
	}

	@RequestMapping(value = "form")
	public String form(StoreInventoryAlert storeInventoryAlert, Model model) {
		model.addAttribute("storeInventoryAlert", storeInventoryAlert);
		Map<Long, String> productMap = Maps.newLinkedHashMap();
		StoreProduct sp = storeInventoryAlert.getStoreProduct();
		if (sp != null) {
			StoreProduct storeProduct = storeProductService.get(sp.getId());
			if (storeProduct.getProduct_type() == StoreProduct.TYPE_SYS) {
				productMap.put(storeProduct.getId(), storeProduct.getProduct().getName());
			} else {
				productMap.put(storeProduct.getId(), storeProduct.getStoreSelfProduct().getName());
			}
		}
		model.addAttribute("productMap", productMap);
		return "modules/inventory/storeInventoryAlertForm";
	}

	@RequestMapping(value = "save")
	public String save(String productIds, StoreInventoryAlert storeInventoryAlert,HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes) {
		Store store = StoreUtils.getStore();
		String [] productList = productIds.split(",");
		int saveSize = 0;
		int modifySize = 0;
		for (String pid : productList) {
			StoreProduct storeProduct = storeProductService.get(Long.parseLong(pid));
			StoreInventoryAlert alertExist = storeInventoryAlertService.isAlertExist(storeProduct);
			StoreInventoryAlert alertProduct = null;
			if (alertExist == null ) {
				alertProduct= new StoreInventoryAlert();
			} else {
				alertProduct = alertExist;
			}
			alertProduct.setStore(store);
			alertProduct.setStoreProduct(storeProduct);
			alertProduct.setAlertAmount(storeInventoryAlert.getAlertAmount());
			if (!beanValidator(model, alertProduct)){
				return form(alertProduct, model);
			}
			Long id = alertProduct.getId();
			storeInventoryAlertService.save(alertProduct);
			if (id == null) {
				saveSize ++;
			} else {
				modifySize ++;
			}
		}
		if (saveSize != 0 && modifySize == 0) {
			addMessage(redirectAttributes, "保存"+saveSize+"个产品的库存预警");
		}
		if (saveSize == 0 && modifySize != 0) {
			addMessage(redirectAttributes, "修改"+modifySize+"个产品的库存预警");
		}
		if (saveSize != 0 && modifySize != 0) {
			addMessage(redirectAttributes, "保存"+saveSize+"个,修改"+modifySize+"个产品的库存预警");
		}
		return "redirect:"+Global.ADMIN_PATH+"/inventory/storeInventoryAlert/";
	}
	
	@RequestMapping(value = "delete")
	public String delete(Long id, RedirectAttributes redirectAttributes) {
		storeInventoryAlertService.delete(id);
		addMessage(redirectAttributes, "删除库存预警成功");
		return "redirect:"+Global.ADMIN_PATH+"/inventory/storeInventoryAlert/";
	}
	
	@ResponseBody
	@RequestMapping(value = "storeProductData")
	public String storeProductData(@RequestParam(required=false) int type, HttpServletResponse response) {
		response.setContentType("application/json; charset=UTF-8");
		Set<Map<String, Object>> set = Sets.newHashSet();
		List<StoreProduct> productList = storeProductService.findByStatus(type, -1);
		List<StoreInventoryAlert> storeProductAlertList = storeInventoryAlertService.findStoreProduct();
		List<StoreProduct> existStoreProductAlert = Lists.newArrayList();
		for (StoreInventoryAlert storeInventoryAlert : storeProductAlertList) {
			existStoreProductAlert.add(storeInventoryAlert.getStoreProduct());
		}
		productList.removeAll(existStoreProductAlert);
		for (StoreProduct storeProduct : productList) {
			Map<String, Object> map = Maps.newHashMap();
			
			if(StoreCare.TYPE_SYS == type) {
				if(storeProduct.getProduct().getStatus() == Product.FLAG_DISABLE){
					continue;
				}
				map.put("name", storeProduct.getProduct().getName());
			} else {
				if(storeProduct.getStoreSelfProduct().getStatus() == StoreSelfProduct.FLAG_DISABLE){
					continue;
				}
				map.put("name", storeProduct.getStoreSelfProduct().getName());
			}
			map.put("id", storeProduct.getId());
			set.add(map);
		}
		return JsonMapper.getInstance().toJson(set);
	}
}
